const config = require('../config.js');
const network = require('../utils/network.js');
const app = getApp();
var doingLogin  = false;//是否正在登陆
var loginCallbackList = [];//登陆后Callback函数

//登录函数
function login(callback) {
  var that = this;
  if (callback){
    loginCallbackList.push(callback);
  }
  var code;
  var userCarId = wx.getStorageSync(userCarId);
  if (!doingLogin){
    doingLogin = true;
    wx.login({
      success: function (res) {
        code = res.code;
        wx.getUserInfo({
          success: function (res) {
            var _userInfo = res.userInfo;
            wx.showLoading({
              title: '正在登陆',
              mask: true,
              success: function () {
                wx.request({
                  url: config.loginUrl,
                  data: {
                    'code': code,
                    'nickName': _userInfo.nickName,
                    'image': _userInfo.avatarUrl,
                    'gender': _userInfo.gender
                  },
                  header: {
                    'content-type': 'application/x-www-form-urlencoded',
                  },
                  method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
                  // header: {}, // 设置请求的 header
                  success: function (res) {
                    doingLogin = false;
                    wx.hideLoading();
                    if (res.data.state) {
                      app.globalData['sessionId'] = res.data.sessionId;
                      app.globalData['userInfo'] = _userInfo;
                      app.globalData.userInfo['nickName'] = res.data.nickName;

                      wx.setStorageSync('token', res.data.token);
                      for (var i in loginCallbackList){
                        typeof loginCallbackList[i] == "function" && loginCallbackList[i]();
                      }
                      loginCallbackList = [];
                    } else {
                      wx.showToast({
                        icon: 'loading',
                        title: '登陆失败',
                        duration: 1500
                      })
                    }
                  }, fail: function () {
                    wx.hideLoading();
                    wx.showToast({
                      icon: 'loading',
                      title: '登陆失败',
                      duration: 1500
                    })
                  }
                })
              }
            })
          },
          fail: function (res) {
            doingLogin = false;
            wx.navigateTo({
              url: '../login/login',
            })
          }
        })
      }
    })
  }
}

module.exports = {
  login: login
}